package com.example.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.dao.CategoryDao;
import com.example.dao.CommodityDao;
import com.example.dao.UserDao;
import com.example.domain.*;
import com.example.service.CategoryService;
import com.example.service.CommodityService;
import com.example.utils.UploadUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;

@Controller
@RequestMapping("commodity")
public class CommodityController {

    @Autowired
    private CommodityService commodityService;
    @Autowired
    private CategoryService categoryService;

    @GetMapping("toCommodity")
    public String toSeek() {
        return "commodity/commodity";
    }

    @GetMapping("/getPage")
    @ResponseBody
    public TableData getPage(Integer page, Integer limit, String name, String username) {

        return commodityService.getPage(page, limit, name, username);
    }

    //    @GetMapping("getAllCommodity")
//    public TableData getAllCommodity(){
//        TableData tableData = new TableData();
//        tableData.setCode(0);
//        tableData.setData(commodityService.list(null));
//        return tableData;
//    }
    @PostMapping("updateCommodity")
    @ResponseBody
    public DataJson updateCommodity(@RequestBody Commodity commodity) {
        DataJson dataJson = new DataJson();
        commodityService.updateById(commodity);
        dataJson.setCode(0);
        dataJson.setMsg("修改成功");

        return dataJson;

    }

    @PostMapping("addCommodity")
    @ResponseBody
    public DataJson addCategory(@RequestBody Commodity commodity) {
        commodityService.save(commodity);
        DataJson dataJson = new DataJson();
        dataJson.setCode(0);
        return dataJson;
    }

    @PostMapping("deleteCommodity")
    @ResponseBody
    public DataJson deleteCategory(@RequestParam("id") Integer id) {
        commodityService.removeById(id);
        DataJson dataJson = new DataJson();
        dataJson.setCode(0);
        return dataJson;
    }

    @PostMapping("batchDeleteCommodity")
    @ResponseBody
    public DataJson batchDeleteCommodity(@RequestParam("ids[]") Integer ids[]) {
        System.out.println("testd------>" + Arrays.toString(ids));

        commodityService.removeByIds(Arrays.asList(ids));
        DataJson dataJson = new DataJson();
        dataJson.setCode(0);
        dataJson.setMsg("删除成功");
        return dataJson;
    }

    @RequestMapping("image")
    @ResponseBody
    public DataJson image(MultipartFile file) {
        //调用工具类完成文件上传
        String imagePath = UploadUtils.upload(file);

        System.out.println(imagePath);

        DataJson dataJson = new DataJson();
        if (imagePath != null) {
            //创建一个HashMap用来存放图片路径
            HashMap hashMap = new HashMap();
            hashMap.put("src", imagePath);
            dataJson.setCode(0);
            dataJson.setMsg("上传成功");
            dataJson.setData(hashMap);
        } else {
            dataJson.setCode(1);
            dataJson.setMsg("上传失败");
        }
        return dataJson;
    }


    @PostMapping("getCount")
    @ResponseBody
    public Result getCount() {
        Result result = new Result();
        Map data = new HashMap();
        List categoryName = new ArrayList();
        List sale = new ArrayList();
        List sold = new ArrayList();
        List<Category> categoryListlist = categoryService.list(null);
        LambdaQueryWrapper<Commodity> lambdaQueryWrapper = new LambdaQueryWrapper();
        for (Category category : categoryListlist) {
            categoryName.add(category.getCateName());
            lambdaQueryWrapper.eq(Commodity::getCategoryId, category.getId()).eq(Commodity::getStatus, 0);
            List<Commodity> saleCommodity = commodityService.list(lambdaQueryWrapper);
            sale.add(saleCommodity.size());
            lambdaQueryWrapper.clear();
            lambdaQueryWrapper.eq(Commodity::getCategoryId, category.getId()).eq(Commodity::getStatus, 2);
            List<Commodity> soldCommodity = commodityService.list(lambdaQueryWrapper);
            sold.add(soldCommodity.size());
            lambdaQueryWrapper.clear();
        }
        data.put("categoryName", categoryName);
        data.put("sale", sale);
        data.put("sold", sold);


        return Result.success(data);
    }

    //微信端
    @Autowired
    private CommodityDao commodityDao;

    @Autowired
    private CategoryDao categoryDao;
    @Autowired
    private UserDao userDao;

    @GetMapping("getCommodityByCategoryId")
    @ResponseBody
    public Result getCommodityByCategoryId(Integer id, Integer page, Integer limit) {
        Result result = new Result();
        LambdaQueryWrapper<Commodity> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(id != null, Commodity::getCategoryId, id);
        Integer status[] = {0, 1};
        lambdaQueryWrapper.in(Commodity::getStatus, status).orderByDesc(Commodity::getId);

        IPage<Commodity> ipage = new Page(page, limit);
        IPage<Commodity> commodityIPage = commodityDao.selectPage(ipage, lambdaQueryWrapper);

        for (Commodity commodity : commodityIPage.getRecords()) {

            if (commodity.getStatus() == 0) {
                commodity.setStatusName("在售");
            } else if (commodity.getStatus() == 1) {
                commodity.setStatusName("正在交易");
            }

            User user = userDao.selectById(commodity.getUserId());
            commodity.setUsername(user.getUsername());
        }

        System.out.println(commodityIPage.getRecords());

        return Result.success(commodityIPage.getRecords());
    }

    @GetMapping("getCommodityById")
    @ResponseBody
    public Result getCommodityById(Integer id) {
        Commodity commodity = commodityService.getById(id);
        User user = userDao.selectById(commodity.getUserId());

        commodity.setUsername(user.getUsername());

        if (commodity.getStatus() == 0) {
            commodity.setStatusName("在售");
        } else if (commodity.getStatus() == 1) {
            commodity.setStatusName("正在交易");
        } else if (commodity.getStatus() == 2) {
            commodity.setStatusName("已售出");
        }

        return Result.success(commodity);
    }

    @GetMapping("getAllCommodity")
    @ResponseBody
    public Result getAllCommodity(Integer page, Integer limit) {
        Result result = new Result();
//        commodityService.list(null);
        LambdaQueryWrapper<Commodity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        Integer status[] = {0, 1};
        lambdaQueryWrapper.in(Commodity::getStatus, status).orderByDesc(Commodity::getId);
        IPage<Commodity> ipage = new Page(page, limit);
        IPage<Commodity> commodityIPage = commodityDao.selectPage(ipage, lambdaQueryWrapper);
        for (Commodity commodity : commodityIPage.getRecords()) {

            if (commodity.getStatus() == 0) {
                commodity.setStatusName("在售");
            } else if (commodity.getStatus() == 1) {
                commodity.setStatusName("正在交易");
            }
//            else if (commodity.getStatus() == 2) {
//                commodity.setStatusName("已售出");
//            }

            User user = userDao.selectById(commodity.getUserId());
            commodity.setUsername(user.getUsername());
        }

        return Result.success(commodityIPage.getRecords());
    }

    @GetMapping("getCommodityByName")
    @ResponseBody
    public Result getCommodityByName(String name) {
        LambdaQueryWrapper<Commodity> lambdaQueryWrapper = new LambdaQueryWrapper();
        Integer status[] = {0, 1};
        lambdaQueryWrapper.like(name != null, Commodity::getName, name).in(Commodity::getStatus, status);
        List<Commodity> commodityList = commodityService.list(lambdaQueryWrapper);

        for (Commodity commodity : commodityList) {
            if (commodity.getStatus() == 0) {
                commodity.setStatusName("在售");
            } else if (commodity.getStatus() == 1) {
                commodity.setStatusName("正在交易");
            }

            User user = userDao.selectById(commodity.getUserId());
            commodity.setUsername(user.getUsername());
        }

        return Result.success(commodityList);
    }

    @RequestMapping("upload")
    @ResponseBody
    public Result upload(MultipartFile file) {
        //调用工具类完成文件上传
        String imagePath = UploadUtils.upload(file);

        Result result = new Result();
        if (imagePath != null) {
            //创建一个HashMap用来存放图片路径

            return Result.success(imagePath);
        } else {
            return Result.error("上传失败");
        }

    }

    @PostMapping("publishCommodity")
    @ResponseBody
    public Result publishCommodity(String name, Double price, String categoryName, String description, String icon, Integer status, Integer userId) {
        Commodity commodity = new Commodity();
        commodity.setName(name);
        commodity.setPrice(price);
        commodity.setCategoryName(categoryName);
        commodity.setDescription(description);
        commodity.setIcon(icon);
        commodity.setStatus(status);
        commodity.setUserId(userId);

        LambdaQueryWrapper<Category> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(categoryName != null, Category::getCateName, categoryName);
        List<Category> list = categoryService.list(lambdaQueryWrapper);
        System.out.println(list);
        commodity.setCategoryId(list.get(0).getId());
        commodityService.save(commodity);
        return Result.success("发布成功");

    }


    @GetMapping("getAllPublish")
    @ResponseBody
    public Result getAllPublish(Integer id, Integer page, Integer limit) {
        LambdaQueryWrapper<Commodity> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(id != null, Commodity::getUserId, id);

        IPage<Commodity> ipage = new Page(page, limit);
        IPage<Commodity> commodityIPage = commodityDao.selectPage(ipage, lambdaQueryWrapper);
        for (Commodity commodity : commodityIPage.getRecords()) {
            Category category = categoryDao.selectById(commodity.getCategoryId());
            User user = userDao.selectById(commodity.getUserId());
            commodity.setCategoryName(category.getCateName());
            commodity.setUsername(user.getUsername());

            User user1 = userDao.selectById(commodity.getPurchaserId());

            if (user1 != null) {
                commodity.setPurchaserName(user1.getUsername());
            }
            if (commodity.getStatus() == 0) {
                commodity.setStatusName("在售");
            } else if (commodity.getStatus() == 1) {
                commodity.setStatusName("正在交易");
            } else if (commodity.getStatus() == 2) {
                commodity.setStatusName("已售出");
            }

        }

        return Result.success(commodityIPage.getRecords());
    }

    @GetMapping("getAllBuy")
    @ResponseBody
    public Result getAllBuy(Integer id, Integer page, Integer limit) {
        LambdaQueryWrapper<Commodity> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(id != null, Commodity::getPurchaserId, id);

        IPage<Commodity> ipage = new Page(page, limit);
        IPage<Commodity> commodityIPage = commodityDao.selectPage(ipage, lambdaQueryWrapper);

        for (Commodity commodity : commodityIPage.getRecords()) {
            Category category = categoryDao.selectById(commodity.getCategoryId());
            User user = userDao.selectById(commodity.getUserId());
            commodity.setCategoryName(category.getCateName());
            commodity.setUsername(user.getUsername());
            if (commodity.getStatus() == 1) {
                commodity.setStatusName("正在交易");
            } else if (commodity.getStatus() == 2) {
                commodity.setStatusName("交易完成");
            }
        }
        return Result.success(commodityIPage.getRecords());
    }

    @PostMapping("confirm")
    @ResponseBody
    public Result confirm(Integer id) {
        System.out.println(id);
        Commodity commodity = commodityService.getById(id);
        System.out.println(commodity);
        commodity.setStatus(2);
        commodityService.updateById(commodity);
        return Result.success("收货成功");
    }

    @PostMapping("buy")
    @ResponseBody
    public Result buy(Integer id, Integer userId) {
        Commodity commodity = commodityService.getById(id);

        commodity.setStatus(1);
        commodity.setPurchaserId(userId);

        commodityService.updateById(commodity);

        return Result.success("购买成功");
    }


    @PostMapping("delete")
    @ResponseBody
    public Result delete(Integer id) {


        commodityService.removeById(id);

        return Result.success("删除成功");
    }


}

